package com.ztt.vxchat.timer;


import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.watchers.DelayWatcher;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ReUtil;
import cn.hutool.cron.CronException;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.TaskTable;
import cn.hutool.cron.task.Task;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ztt.vxchat.controller.VXController;
import com.ztt.vxchat.utils.SwitchInfoUtil;
import com.ztt.vxchat.utils.SwitchJsonUtil;
import com.ztt.vxchat.utils.SwitchUtil;
import com.ztt.vxchat.utils.ToolsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.time.LocalDateTime;
import java.util.List;

/**
* @project_name vx-chat
* @author ztt
* @description []
* @date 2022/8/23 12:45
*/
public class TaskTimer {

    @Value("${custom-default.message}")
    String messageDefaultContent;


    public String   start(){

//        停止所有定时任务
        List<Task> tasks = CronUtil.getScheduler().getTaskTable().getTasks();
        try{
            if(tasks.size() > 0){
                CronUtil.stop();
            }
        }catch (IllegalStateException e){
            System.out.println("没有运行中的定时任务");
        }


//        每两个小时获取一次TOKEN
        CronUtil.schedule("0 0 0/2 * * ? ", new Task() {
            @Override
            public void execute() {
                new VXController().getToken();
            }
        });


//        如果没有消息文件则初始化消息文件
        String messagePath = ToolsUtil.getNowProjectPath()+"/message.json";
        FileReader fileReader = null;
        try {
            fileReader= new FileReader(messagePath);
        }catch (IORuntimeException e) {
            FileUtil.writeUtf8String(messageDefaultContent,messagePath);
        }


        String messageStr = fileReader.readString();


//        原生消息格式化成JSON
        JSONArray messageArr = JSONUtil.parseArray(messageStr);
        for (Object obj : messageArr) {

            JSONObject messageJson = JSONUtil.parseObj(obj);

            String cronExp = messageJson.getStr("cronExp");


//            先推一次
            JSONObject handlerMessageJson = SwitchJsonUtil.handler(messageJson);
            new VXController().sendTemplateMessage(handlerMessageJson);


//            创建定时任务
            try{
                CronUtil.schedule(cronExp, new Task() {
                    @Override
                    public void execute() {
                        JSONObject handlerMessageJson = SwitchJsonUtil.handler(messageJson);
                        new VXController().sendTemplateMessage(handlerMessageJson);
                    }
                });

                // 支持秒级别定时任务
                CronUtil.setMatchSecond(true);

            }catch (CronException e){
                Console.log("cron表达式错误：" + cronExp);
            }

        }

        try{
            CronUtil.start();
        }catch (UtilException e){
            Console.log("已经有定时任务啦");
        }

        WatchMonitor monitor = WatchMonitor.createAll(messagePath, new DelayWatcher(new SimpleWatcher(){
            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                Console.log("刷新配置文件");
                start();
            }
        }, 5000));

        monitor.start();

        return "完成";
    }


}
